<template>
    <div class="system-custom-ratings-container">
        <el-form :inline="true" ref="form" class="system-search-form" :model="searchForm">
            <el-form-item>
                <el-cascader
                    class="go-out"
                    v-model="searchForm.mechanism"
                    :options="mechanismList"
                    :show-all-levels="false"
                    :props="{ checkStrictly: true, emitPath: false }"
                    filterable
                    size="small">
                </el-cascader>
            </el-form-item>
            <el-form-item>
                <el-select v-model="searchForm.type" filterable clearable placeholder="请选择类型" size="small">
                    <el-option
                        v-for="item in typeOptions"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button class="sub-btn" type="primary" size="small" @click="getData">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="table-box">
            <div class="title">
                <el-button class="add-btn" type="primary" icon="el-icon-plus" size="small" v-auth="{code: 300006001001}" @click="showAddDialog">新增评分项</el-button>
                <div class="score">
                    <p>{{totalScore}}分</p>
                    <p>总分</p>
                </div>
            </div>
            <el-tabs v-model="activeNameTable">
                <el-tab-pane name="index" label="首页">
                    <el-table
                        ref="tableData"
                        :data="tableData"
                        tooltip-effect="light"
                        border
                        :max-height="tableHeight"
                        class="data-table">
                        <el-table-column
                            label="序号"
                            type="index"
                            align="center"
                            width="50">
                        </el-table-column>
                        <el-table-column
                            label="类型"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{scope.row.messageType | getInfoType1}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="类别"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{scope.row.messageClass | getInfoType2}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="类别"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span :class="{'type-yellow': scope.row.scoreType}">{{scope.row.scoreType | getScoreType}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="name"
                            align="center"
                            label="评分项"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="scoreValue"
                            align="center"
                            label="分值"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-button type="text" v-if="scope.row.scoreType === 1" v-auth="{code: 300006001002}" size="small" @click="tableEdit(scope.$index, scope.row)">
                                    编辑
                                </el-button>
                                <el-button type="text" v-if="scope.row.scoreType === 1" v-auth="{code: 300006001002}" size="small" @click="tableDelete(scope.row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane name="appendix" label="附页" disabled></el-tab-pane>
            </el-tabs>
        </div>
        <el-dialog
            :title="isAdd ? '新增院标评分' : '编辑院标评分'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            @close="closeDialog"
            center
            width="40%">
            <el-form :inline="false" ref="dialogForm" class="dialog-form" :rules="editFormRules" :model="editForm" label-width="100px">
                <el-form-item label="关联类型" prop="relatedType">
                    <el-select v-model="editForm.relatedType" placeholder="请选择关联类型" size="small">
                        <el-option
                            v-for="item in typeOptions"
                            :key="item.key"
                            :label="item.value"
                            :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="关联项" prop="relatedItems">
                    <el-select v-model="editForm.relatedItems" filterable placeholder="请选择关联项" size="small">
                        <el-option
                            v-for="(item, index) in GBList"
                            :key="index"
                            :label="item.name"
                            :value="item.field">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="评分项名称" prop="name">
                    <el-input type="text" maxlength="100" v-model="editForm.name" placeholder="请输入评分项名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="分值" prop="score">
                    <el-input type="text" v-model="editForm.score" onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')" placeholder="请输入分值" size="small"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('dialogForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getScoreMSList, getGBList, saveScore, getRowItem, deleteRow} from '@/api/system/custom-rating'

    export default {
        name: 'index',
        data () {
            return {
                // 搜索表单
                searchForm: {
                    mechanism: '',
                    type: 1
                },
                // 关联项列表
                GBList: [],
                // 表格数据
                tableData: [],
                // 表格高度
                tableHeight: 100,
                // 显示弹框
                dialogVisible: false,
                // 弹框表单
                editForm: {
                    relatedType: '',
                    relatedItems: '',
                    name: '',
                    score: ''
                },
                // 机构列表
                mechanismList: [],
                // 关联类型
                typeOptions: [
                    {'key': 1, 'value': '患者基本信息'},
                    {'key': 2, 'value': '住院过程信息'},
                    {'key': 3, 'value': '诊疗信息'},
                    {'key': 4, 'value': '费用信息'}
                ],
                // 是否新增
                isAdd: true,
                // 总分
                totalScore: 0,
                // 当前标签页
                activeNameTable: 'index',
                editFormRules: {
                    relatedType: [
                        {required: true, message: '请选择关联类型', trigger: 'change'}
                    ],
                    relatedItems: [
                        {required: true, message: '请选择关联项', trigger: 'change'}
                    ],
                    name: [
                        {required: true, message: '请填写评分项名称', trigger: ['blur', 'change']}
                    ],
                    score: [
                        {required: true, message: '请填写分值', trigger: ['blur', 'change']}
                    ]
                },
                // 使用储存的数据，不去请求
                useStoreData: false,
                useStoreGB: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStoreData = this.$route.query.tags === 'tags'
            this.useStoreGB = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
            this.tableHeight = height > 107 ? height : 107
            this.getMechanismList()
            this.initData()
            this.getData()
            this.getRelatedItemsList()
        },
        mounted () {
            window.onresize = () => {
                // 213=其他元素高度60+50+48+55 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            /**
             * 初始化页面参数
             */
            initData () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (JSON.stringify(query) !== '{}') {
                    this.searchForm.mechanism = query.organId
                    this.searchForm.type = query.messageType
                }
            },
            /**
             * 获取机构列表
             */
            getMechanismList () {
                let mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                let parentList = []
                mechanismList.forEach(item => {
                    // 一级机构
                    if (!item.pid) {
                        parentList.push({
                            value: item.id,
                            label: item.name,
                            children: []
                        })
                        // 有一级机构的二级机构
                        mechanismList.forEach(it => {
                            if (it.pid === item.id) {
                                parentList[parentList.length - 1].children.push({
                                    value: it.id,
                                    label: it.name,
                                    children: null
                                })
                            }
                        })
                        if (!parentList[parentList.length - 1].children.length) {
                            parentList[parentList.length - 1].children = null
                        }
                    } else {
                        // 二级机构
                        let parent = mechanismList.filter(i => item.pid === i.id)
                        if (!parent.length) {
                            parentList.push({
                                value: item.id,
                                label: item.name,
                                children: null
                            })
                        }
                    }
                })
                this.mechanismList = parentList
                if (this.mechanismList.length) {
                    if (this.getLocalStorage('userMechanism', 'id') && this.hasMechanismId(this.getLocalStorage('userMechanism', 'id'))) {
                        this.searchForm.mechanism = this.getLocalStorage('userMechanism', 'id')
                    } else {
                        this.searchForm.mechanism = parentList[0].value
                    }
                }
            },
            /**
             * 判断所属机构是否在组织机构中
             * @param id 所属机构id
             */
            hasMechanismId (id) {
                let res = this.mechanismList.filter(item => item.value === id)
                return res.length !== 0
            },
            /**
             * 获取表格数据
             */
            getData () {
                let params = {
                    organId: this.searchForm.mechanism || null,
                    messageType: this.searchForm.type || null
                }
                this.setGetStore(this.$route.name, params)
                if (this.getSession(this.$route.name, 'getScoreMSList') && this.useStoreData) {
                    this.useStoreData = false
                    let res = this.getSession(this.$route.name, 'getScoreMSList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.result.rows
                        this.totalScore = res.data.totalScore
                    }
                } else {
                    getScoreMSList(params).then(res => {
                        this.useStoreData = false
                        this.setSession(this.$route.name, {getScoreMSList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.result.rows
                            this.totalScore = res.data.totalScore
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 关联项
             */
            getRelatedItemsList () {
                if (this.getSession(this.$route.name, 'getGBList') && this.useStoreGB) {
                    this.useStoreGB = false
                    let res = this.getSession(this.$route.name, 'getGBList')
                    if (res.code.toString() === '200') {
                        this.GBList = res.data
                    }
                } else {
                    getGBList().then(res => {
                        this.useStoreGB = false
                        this.setSession(this.$route.name, {getGBList: res})
                        if (res.code.toString() === '200') {
                            this.GBList = res.data
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 启动停止
             * @param row 行数据
             */
            tableDelete (row) {
                let text = `您确定删除"${row.name}"评分项吗?`
                let title = '删除评分项'
                this.$confirm(text, title, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.deleteRowData(row.id)
                }).catch()
            },
            /**
             * 删除行数据
             * @param id 数据id
             */
            deleteRowData (id) {
                deleteRow(id).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success('删除成功')
                        this.getData()
                    } else {
                        this.$message.error(res.message)
                        this.getData()
                    }
                })
            },
            /**
             * 编辑表格内容
             * @param index 索引
             * @param row 行数据
             */
            tableEdit (index, row) {
                this.isAdd = false
                getRowItem(row.id).then(res => {
                    if (res.code.toString() === '200') {
                        this.editForm = {
                            relatedType: res.data.messageType,
                            relatedItems: res.data.field,
                            name: res.data.name,
                            score: res.data.scoreValue,
                            id: row.id
                        }
                    } else {
                        this.$message.error(res.message)
                    }
                })
                this.dialogVisible = true
            },
            /**
             * 关闭弹框
             */
            closeDialog () {
                this.editForm = {
                    relatedType: '',
                    relatedItems: '',
                    name: '',
                    score: ''
                }
                this.$refs['dialogForm'].resetFields()
                this.dialogVisible = false
            },
            /**
             * 点击新增打开弹窗
             */
            showAddDialog () {
                this.isAdd = true
                this.dialogVisible = true
            },
            /**
             * 提交弹框表单
             * @param formName 表单名
             */
            submitEditForm (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params = {
                            organId: this.searchForm.mechanism,
                            JoinID: this.getGBId(this.editForm.relatedItems),
                            name: this.editForm.name,
                            scoreValue: Number(this.editForm.score)
                        }
                        if (!this.isAdd) params.id = this.editForm.id
                        saveScore(params).then(res => {
                            if (res.code.toString() === '200') {
                                this.$message.success('保存成功')
                                this.closeDialog()
                                this.getData()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    } else {
                        return false
                    }
                })
            },
            /**
             * 获取关联项id
             * @param val 对应字段
             */
            getGBId (val) {
                let res = this.GBList.filter(item => item.field === val)
                return res[0] ? res[0].id : ''
            }
        },
        filters: {
            getInfoType1 (val) {
                switch (val) {
                case 1:
                    return '患者基本信息'
                case 2:
                    return '住院过程信息'
                case 3:
                    return '诊疗信息'
                case 4:
                    return '费用信息'
                }
            },
            getInfoType2 (val) {
                switch (val) {
                case 1:
                    return 'A类'
                case 2:
                    return 'B类'
                case 3:
                    return 'C类'
                case 4:
                    return 'D类'
                }
            },
            getScoreType (val) {
                return val ? '院标' : '国标'
            }
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .system-custom-ratings-container {
        .system-search-form {
            .el-form-item {
                margin-bottom: 0;
            }
        }
        .table-box {
            background: #fff;
            padding: 10px;
            box-sizing: border-box;
            height: calc(100vh - 183px);
            .title {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                .add-btn {
                }
                .score {
                    padding-right: 20px;
                    p {
                        margin: 0;
                        text-align: center;
                    }
                    p:first-child {
                        font-size: 20px;
                        font-weight: 600;
                        color: #f2ab66;
                    }
                    p:last-child {
                        font-size: 12px;
                        margin-top: 6px;
                    }
                }
            }
        }
        .type-yellow {
            color: #f2ab66;
        }
        /deep/.el-dialog {
            width: 800px!important;
            .el-dialog__body {
                padding: 10px;
                .dialog-form {
                    width: 90%;
                    margin: 0 auto;
                }
            }
            .el-dialog__footer {
                text-align: right;
            }
        }
    }
</style>
